<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AdminLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'user_name',
        'action',
        'module',
        'model_type',
        'model_id',
        'description',
        'old_data',
        'new_data',
        'ip_address',
        'user_agent',
        'url',
        'method',
    ];

    protected $casts = [
        'old_data' => 'array',
        'new_data' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 关联用户
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 记录日志
     */
    public static function record(
        string $action,
        string $module,
        string $description,
        ?string $modelType = null,
        ?int $modelId = null,
        ?array $oldData = null,
        ?array $newData = null
    ): void {
        $user = auth()->user();
        
        self::create([
            'user_id' => $user?->id,
            'user_name' => $user?->name ?? $user?->email ?? $user?->phone ?? 'Guest',
            'action' => $action,
            'module' => $module,
            'model_type' => $modelType,
            'model_id' => $modelId,
            'description' => $description,
            'old_data' => $oldData,
            'new_data' => $newData,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'url' => request()->fullUrl(),
            'method' => request()->method(),
        ]);
    }

    /**
     * 获取操作类型的中文名称
     */
    public function getActionNameAttribute(): string
    {
        return match($this->action) {
            'create' => '创建',
            'update' => '更新',
            'delete' => '删除',
            'view' => '查看',
            'login' => '登录',
            'logout' => '登出',
            'export' => '导出',
            'import' => '导入',
            default => $this->action,
        };
    }

    /**
     * 获取模块的中文名称
     */
    public function getModuleNameAttribute(): string
    {
        return match($this->module) {
            'products' => '产品管理',
            'orders' => '订单管理',
            'users' => '用户管理',
            'categories' => '分类管理',
            'system-settings' => '系统设置',
            'specification-templates' => '规格模板',
            default => $this->module,
        };
    }
}
